package com.lionxing.DNTG;

import org.cocos2d.actions.base.CCAction;
import org.cocos2d.actions.instant.CCCallFuncND;
import org.cocos2d.actions.interval.CCMoveTo;
import org.cocos2d.actions.interval.CCSequence;
import org.cocos2d.events.CCTouchDispatcher;
import org.cocos2d.layers.CCLayer;
import org.cocos2d.layers.CCScene;
import org.cocos2d.menus.CCMenu;
import org.cocos2d.menus.CCMenuItemSprite;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.nodes.CCLabel;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.nodes.CCSpriteFrame;
import org.cocos2d.nodes.CCTextureCache;
import org.cocos2d.opengl.CCBitmapFontAtlas;
import org.cocos2d.opengl.CCTexture2D;
import org.cocos2d.types.CGPoint;
import org.cocos2d.types.CGRect;
import org.cocos2d.types.CGSize;

import android.view.MotionEvent;


public class PlayLayer extends CCLayer{

	Tile selectedTile;
	Tile firstOne;
	
	boolean isMoving;
	
	int value;
    int _step;
    CCBitmapFontAtlas label;
	Box box;
	
	float _widthx;
	float _heighty;
	
	CCSprite spSp;
	CCSprite bgSp;
	
	CGPoint _touchpoint;
	
	boolean _ismove;
	
	public static CCScene scene(int pic) {
		CCScene scene = CCScene.node();
		PlayLayer layer = new PlayLayer(pic);
		scene.addChild(layer);
		
		return scene;
	}
	
	  protected PlayLayer() 
	  {
		  
		  
	  }

    protected PlayLayer(int name) 
    {

    	String namestring = String.format("%d.png", name);
    	
		CGSize size = CCDirector.sharedDirector().winSize();
		
		spSp= CCSprite.sprite(namestring);
		
		value = name;
		
		spSp.setScaleX((size.width/GameDefine.KIos_W));
		spSp.setScaleY((size.height/GameDefine.KIos_h));
		spSp.setPosition(CGPoint.make(size.width/2, size.height/2));
		//Log.
		addChild(spSp, -1);
		
		
		schedule("autoremove", 1.0f);

		_ismove =false;

    }
    
    
    @Override
    public boolean ccTouchesBegan(MotionEvent event) {
    	
    	if(_ismove)
    	{
    		return true;
    	}
    	
    	playSound.sharedDirector().playEffectSound(R.raw.kick);
        CGPoint convertedLocation = CCDirector.sharedDirector()
        	.convertToGL(CGPoint.make(event.getX(), event.getY()));

        if (convertedLocation.y < (GameDefine.kStartY) || convertedLocation.y > (GameDefine.kStartY + (GameDefine.kTileSize*_heighty * GameDefine.kBoxHeight))) {
        	return CCTouchDispatcher.kEventIgnored;
    	}
    	
    	int x = (int)(convertedLocation.x - GameDefine.kStartX*_widthx) / (int)(GameDefine.kTileSize*_widthx);
    	int y = (int)(convertedLocation.y - GameDefine.kStartY*_heighty) / (int)(GameDefine.kTileSize*_heighty);
    	
    	if (selectedTile != null && selectedTile.x == x && selectedTile.y == y) {
 			selectedTile.sprite.setPosition(_touchpoint);
			selectedTile.sprite.setScaleX(1.0f);
			selectedTile.sprite.setScaleY(1.0f);
    		selectedTile = null;
    		return CCTouchDispatcher.kEventIgnored;
    	}
    	
    	Tile tile = box.getTile(x, y);
    	if (tile.x >= 0 && tile.y >= 0) {
    		if (selectedTile != null && selectedTile.nearTile(tile) ){
    			box.setLock(true);
    			//[self changeWithTileA: selectedTile TileB: tile sel: @selector(check:data:)];
    			selectedTile.sprite.setPosition(_touchpoint);
    			selectedTile.sprite.setScaleX(1.0f);
    			selectedTile.sprite.setScaleY(1.0f);
    			this.changeWithTileA(selectedTile, tile);
    			selectedTile = null;
    		}
    		else {
    			if (selectedTile!= null) {
    				if (selectedTile.x == x && selectedTile.y == y) {
    	    			selectedTile.sprite.setPosition(_touchpoint);
    	    			selectedTile.sprite.setScaleX(1.0f);
    	    			selectedTile.sprite.setScaleY(1.0f);
    					selectedTile = null;
    				}
    			}
    			selectedTile = tile;
    			
    			bgSp.removeChild(selectedTile.sprite, true);
    			_touchpoint = selectedTile.sprite.getPosition();
    			
    			selectedTile.sprite.setPosition(_touchpoint.x,_touchpoint.y+1);
    			selectedTile.sprite.setScaleX(1.1f);
    			selectedTile.sprite.setScaleY(1.1f);
    			
    			bgSp.addChild(selectedTile.sprite, 217);
    			
    			
    			
    		}
    	}

        
        return CCTouchDispatcher.kEventHandled;
    }
    
    
    public void changeWithTileA(Tile a , Tile b )
    {

    	_ismove = true;
    	
    	CCMoveTo movetoA = CCMoveTo.action(GameDefine.kMoveTileTime, b.sprite.getPosition());
    	
    	CCAction actionA = CCSequence.actions(movetoA,CCCallFuncND.action(this, "check"));
    	
    	CCMoveTo movetoB = CCMoveTo.action(GameDefine.kMoveTileTime, a.sprite.getPosition());
    	
    	//CCAction actionB = CCSequence.actions(movetoB);
    	//[a.sprite runAction:actionA];
    	//[b.sprite runAction:actionB];
    	
    	
    	
    	a.sprite.runAction(actionA);
    	b.sprite.runAction(movetoB);
    	
    	//[a trade:b];
    	
    	a.trade(b);
    	
    	//NSLog(@"Check Solution");
    	
    	Boolean isSolved = box.checkSolution();
    	
    	//CCLabelTTF *solvedLabel = (CCLabelTTF*)[self getChildByTag:kSolvedText];
        
        _step ++;
        //NSString *step = [NSString stringWithFormat:@"The Puzzle step is %d",_step];
        String tmpstring= 	String.format("  %d",_step);
        label.setString(tmpstring);
    	
    	if (isSolved) {
    		//[solvedLabel setString:step];
          // [box movesuccesswithstep:_step];
    		CCScene scene = completeLayer.scene(value,_step);
   		// CCDirector.sharedDirector().replaceScene(scene);
    		 scenemanager.go(scene);
    		
    	} else {
    		//[solvedLabel setString:step];
    	}
    }
    
    public void gotonextMM(int num)
    {
       // [box check:num];
        box.check(num);
        
    }
	
    
    public void backTomenu(Object sender)
    {
    	playSound.sharedDirector().playEffectSound(R.raw.kick);	
    	
		CCScene scene = leveLayer.scene(1);
		 //CCDirector.sharedDirector().replaceScene(scene);
		 scenemanager.go(scene);
    }
    
    public void autoremove(float per)
    {
    	
    	this.removeChild(spSp, true);
    	
    	unschedule("autoremove");
    	
    	this.setIsTouchEnabled(true);


    	//box = [[Box alloc] initWithSize:CGSizeMake(kBoxWidth,kBoxHeight) imgValue:value];
    	CGSize size = CCDirector.sharedDirector().winSize();
    	bgSp = CCSprite.sprite("transfer.png");
		
    	String tmpstring= 	String.format("  %d",_step);
    		
    	 label = CCBitmapFontAtlas.bitmapFontAtlas(tmpstring, "01.fnt");
//    	    lbScore.anchorPoint = ccp(1.0, 1.0);
//    	    lbScore.scale = 0.8;
//    	  
//
//    	    //lbScore.anchorPoint = ccp(0,0);
//    		lbScore.position = ccp(115, 467);
//    		[self addChild:lbScore z:kSolvedText tag:kSolvedText];
    	 
    	label.setAnchorPoint(CGPoint.make(1.0f, 1.0f));
    	label.setScale(0.8f);
    	label.setPosition(CGPoint.make(115, 467));
		
    	bgSp.addChild(label);
    	

    	CCSprite setpng = CCSprite.sprite("step.png");
    	setpng.setPosition(CGPoint.make(35, 460));
    	bgSp.addChild(setpng);
    	
    	
      //  CCTexture2D * texture = [[CCTextureCache sharedTextureCache] addImage:@"quit.png"];
        
        CCTexture2D texture = CCTextureCache.sharedTextureCache().addImage("quit.png");
        
//        CCSpriteFrame* holdimg = NULL;
//        CCSpriteFrame* nomorl = NULL;
        
        CCSpriteFrame holding = null;
        CCSpriteFrame nomorl = null;
        
        for (int i = 0 ; i < 2; i++) {
        

            if (i == 0) 
            {
            	holding = CCSpriteFrame.frame(texture, CGRect.make(i*62, 0, 62, 41),CGPoint.zero());
            }
            else if(i == 1)
            {
            	nomorl = CCSpriteFrame.frame(texture, CGRect.make(i*62, 0, 62, 41),CGPoint.zero());
            }
            
        }
        
     
        
          //  CCSprite* holdsp = [CCSprite spriteWithSpriteFrame:holdimg];
           
        	CCSprite holdsp = CCSprite.sprite(holding);
           // CCSprite* nomorlsp = [CCSprite spriteWithSpriteFrame:nomorl];
        	CCSprite nomorlsp = CCSprite.sprite(nomorl);
           // CCMenuItemSprite *item1 = [CCMenuItemSprite itemFromNormalSprite:nomorlsp selectedSprite: holdsp target:self selector:@selector(backTomenu:)];
            
        	CCMenuItemSprite item1 = CCMenuItemSprite.item(holdsp, nomorlsp, this, "backTomenu");
          //  CCMenu*menu =  [CCMenu menuWithItems:item1,nil];
            
        	CCMenu menu = CCMenu.menu(item1);

            menu.setPosition(CGPoint.make(280, 18));

            
            bgSp.addChild(menu);
            
        
       
            _widthx = size.width/GameDefine.KIos_W;
            _heighty = size.height/GameDefine.KIos_h;
    	
		bgSp.setScaleX(_widthx);
		bgSp.setScaleY(_heighty);
		bgSp.setPosition(CGPoint.make(size.width/2, size.height/2));
		//Log.
		addChild(bgSp, -1);
    	
    	box = new Box(CGSize.make(GameDefine.kBoxWidth, GameDefine.kBoxHeight));
    	box.layer = bgSp;
    	box.lock = false;	
    	
    
    
    	//CCLabelTTF solvedLabel = [CCLabelTTF labelWithString:step fontName:@"Marker Felt" fontSize:18];
    	
        //solvedLabel.anchorPoint = ccp(0,0);
    	//solvedLabel.position = ccp(10, 448);
    	//[self addChild:solvedLabel z:kSolvedText tag:kSolvedText];
        
        boolean isSolved = box.checkSolution();
    	
    	
    	if (isSolved) {
    		//[solvedLabel setString:@"The Puzzle is Solved"];
    	} else {
    		//[solvedLabel setString:@"The Puzzle is NOT Solved"];
    	}
    	
    	gotonextMM(value);
    }
    
    
    public  void check(Object sender)
    {
    	_ismove = false;
    }
    
	 public  void onExit()
		{		
				this.removeAllChildren(true);
				super.onExit();
				
				label = null;

				
				spSp = null;
				bgSp = null;
		}
}
